<?php

namespace app\admin\controller;

use app\common\model\Classes;
use app\common\model\ClassesStu;
use app\common\model\Config;
use app\common\model\OrderShoufei;
use app\common\model\Manager;
use app\common\model\Student;
use app\common\model\Student as studentModel;
use app\common\model\StudentKaoqin;
use app\common\model\UserStudent;
use app\common\model\Withdrawal as WithdrawalModel;
use app\common\model\User as UserModel;
use app\common\model\MoneyLog as MoneyLogModel;
use app\service\LogService;
use app\service\PayService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Db;

class Finance extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    /* 佣金流水 */
    public function moneylog()
    {
        if (request()->isPost()) {
            $where = [
                'type' => 1
            ];
            if ($this->mall_id != 0) {
                $where['mall_id'] = $this->mall_id;
            }
            $input = input();
            if ($input['uid']) {
                $where['uid'] = $input['uid'];
            }
            if ($input['sid']) {
                $where['sid'] = $input['sid'];
            }
            if ($input['order_id']) {
                $where['order_id'] = $input['order_id'];
            }
            $page = max($input['page'], 1);
            $size = 50;
            $list = MoneyLogModel::getPage($where, $page, $size, 'id desc');
            $total = MoneyLogModel::getCount($where);
            if (!$list) {
                return returnJson(0, '', [
                    'list' => [],
                    'size' => $size,
                    'total' => 0
                ]);
            }
            foreach ($list as $k => $v) {
                $list[$k]['userInfo'] = UserModel::getOne(['id' => $v['uid']], 'nickname,id');
            }
            return returnJson(0, '', [
                'list' => $list,
                'size' => $size,
                'total' => $total,
                'page' => $page
            ]);
        }
    }

    /* 积分流水 */
    public function scorelog()
    {
        if (request()->isPost()) {
            $where = [
                'type' => 2
            ];
            if ($this->mall_id != 0) {
                $where['mall_id'] = $this->mall_id;
            }
            $input = input();
            if ($input['uid']) {
                $where['uid'] = $input['uid'];
            }
            if ($input['sid']) {
                $where['sid'] = $input['sid'];
            }
            if ($input['order_id']) {
                $where['order_id'] = $input['order_id'];
            }
            $page = max($input['page'], 1);
            $size = 50;
            $list = MoneyLogModel::getPage($where, $page, $size, 'id desc');
            $total = MoneyLogModel::getCount($where);
            if (!$list) {
                return returnJson(0, '', [
                    'list' => [],
                    'size' => $size,
                    'total' => 0
                ]);
            }
            foreach ($list as $k => $v) {
                $list[$k]['userInfo'] = UserModel::getOne(['id' => $v['uid']], 'nickname,id');
                $list[$k]['studentInfo'] = \app\common\model\Student::getOne(['id' => $v['sid']], 'name,id');
                $classInfo = ClassesStu::getColumn(['sid' => $v['sid']],'cid');
                $list[$k]['classesInfo'] = $classInfo?Classes::getAll(['id' => ['in',$classInfo]],'','id,name,create_time'):[];
            }
            return returnJson(0, '', [
                'list' => $list,
                'size' => $size,
                'total' => $total,
                'page' => $page
            ]);
        }
    }

    /* 收费流水 */
    public function shoufei()
    {
        if (request()->isPost()) {
            $where = [];
            $input = input();
            if ($input['uid']) {
                $where['uid'] = $input['uid'];
            }
            if ($input['sid']) {
                $where['sid'] = $input['sid'];
            }
            if ($input['name']) {
                $mid = Manager::getValue(array('name'=>array('like','%'.$input['name'].'%')),'id');
                if ($mid){
                    $where['mid'] = array(
                        'in' => $mid
                    );
                }
            }
            if($input['update_time']){
                $where['update_time'] = array('between',[strtotime($input['update_time'][0]),strtotime($input['update_time'][1])]);
            }
            $page = max($input['page'], 1);
            $size = 50;
            if ($input['excel']) {

                if (!($input['update_time'])) {
                    return returnJson(1, '必须选择一个时间区间');
                }
                if(ceil((strtotime($input['update_time'][1])-strtotime($input['update_time'][0])/(24*3600)))>31)
                    return returnJson(1, '时间不要超过一个月');
                $list = OrderShoufei::getPage($where, $page, 1000, 'id desc,checked asc');
                $total = OrderShoufei::getCount($where);
            }else{
                $list = OrderShoufei::getPage($where, $page, $size, 'id desc,checked asc');
                $total = OrderShoufei::getCount($where);
            }

            if (!$list) {
                return returnJson(0, '', [
                    'list' => [],
                    'size' => $size,
                    'total' => 0
                ]);
            }
            $manage = Manager::getColumn([],'id,name');
            foreach ($list as $k => $v) {
                $list[$k]['name'] = isset($manage[$v['mid']])?$manage[$v['mid']]:'';
                $list[$k]['student'] = studentModel::getValue(array('id'=>array('=',$v['sid'])),'name');
            }

            if ($input['excel']) {
                //导出excel
                $file = $this->exportShoufei($list);
                return returnJson(0, '', $file);
            }
            return returnJson(0, '', [
                'list' => $list,
                'size' => $size,
                'total' => $total,
                'page' => $page
            ]);
        }
    }

    protected function exportShoufei($list)
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $arrData = [
            ['学员ID', '学员姓名', '金额', '教练', '支付状态']
        ];
        $status = array('待支付','已付款','订单关闭');
        foreach ($list as $k => $v) {
            $arrData[] = [
                $v['sid'],$v['student'], $v['money'], $v['name'], $status[$v['checked']]
            ];
        }

        $sheet->fromArray($arrData, NULL);
        $writer = new Xlsx($spreadsheet);
        $name = '收费信息-' . date('Y-m')  . ".xlsx";
        $path = ROOT_PATH . "public" . DS . "cache" . DS . $name;
        $writer->save($path);
        return request()->domain() . "/cache/" . $name;
    }

    /* 充值币 */
    public function cashlog()
    {
        $where = [
            'type' => 3
        ];
        $input = input();
        if ($input['uid']) {
            $where['uid'] = $input['uid'];
        }
        if ($input['order_id']) {
            $where['order_id'] = $input['order_id'];
        }
        $page = max($input['page'], 1);
        $size = 50;
        $list = MoneyLogModel::getPage($where, $page, $size, 'id desc');
        $total = MoneyLogModel::getCount($where);
        if (!$list) {
            return returnJson(0, '', [
                'list' => [],
                'size' => $size,
                'total' => 0
            ]);
        }
        foreach ($list as $k => $v) {
            $list[$k]['userInfo'] = UserModel::getOne(['id' => $v['uid']], 'nickname,id');
        }
        return returnJson(0, '', [
            'list' => $list,
            'size' => $size,
            'total' => $total,
            'page' => $page
        ]);
    }

    /* 提现记录 */
    public function withdrawal()
    {
        $where = [];
        $input = input();
        if ($input['uid']) {
            $where['uid'] = $input['uid'];
        }
        $page = max($input['page'], 1);
        $size = 50;
        $list = WithdrawalModel::getPage($where, $page, $size, 'id desc');
        $total = WithdrawalModel::getCount($where);

        if (!$list) {
            return returnJson(0, '', [
                'list' => [],
                'size' => $size,
                'total' => 0
            ]);
        }
        foreach ($list as $k => $v) {
            $list[$k]['userInfo'] = UserModel::getOne(['id' => $v['uid']], 'nickname,id');
            if ($v['status'] == 1) {
                $status_text = '待处理';
            } elseif ($v['status'] == 2) {
                $status_text = '已处理';
            } else {
                $status_text = '已退回';
            }
            $list[$k]['status_text'] = $status_text;
        }
        return returnJson(0, '', [
            'list' => $list,
            'size' => $size,
            'total' => $total,
            'page' => $page
        ]);
    }

    /* 充值佣金 */
    public function chargemoney()
    {
        $input = input();
        if (!$input['number'] || !is_numeric($input['number'])) {
            return returnJson(1, '金额填写错误');
        }
        if (!$input['uid']) {
            return returnJson(1, '请填写用户ID');
        }
        if (!$input['note']) {
            return returnJson(1, '请填写备注');
        }
        $userInfo = UserModel::getOne(['id' => $input['uid']]);
        if (!$userInfo) {
            return returnJson(1, '用户不存在');
        }
        $key = "charge-{$input['uid']}-{$input['number']}";
        $cache = cache($key);
        if ($cache) {
            return returnJson(1, '为防止重复充值,请1分钟后再试');
        }
        cache($key, 1, 60);
        UserModel::changeMoney($input['uid'], 1, $input['number'], $input['note'], '', [
            'manager_name' => $this->manager['name'],
            'is_charge' => 1
        ]);
        return returnJson(0, '充值成功');
    }

    /* 充值积分 */
    public function chrgescore()
    {
        $input = input();
        if (!$input['number'] || !is_numeric($input['number'])) {
            return returnJson(1, '金额填写错误');
        }
//        if (!$input['uid']) {
//            return returnJson(1, '请填写用户ID');
//        }
        if (!$input['note']) {
            return returnJson(1, '请填写备注');
        }
        if ($input['uid']) {
            $userInfo = UserModel::getOne(['id' => $input['uid']]);
            if (!$userInfo) {
                return returnJson(1, '用户不存在');
            }
        }
        if ($input['sid']) {
            $studentInfo = \app\common\model\Student::getOne(['id' => $input['sid']]);
            if (!$studentInfo) {
                return returnJson(1, '学员不存在');
            }
            if($input['uid']){
                $userStudent = UserStudent::getOne(['uid' => $input['uid'], 'sid' => $input['sid']]);
                if (!$userStudent ) {
                    return returnJson(1, '该家长未绑定该学员');
                }
            }

        }
//        $key = "charge-{$input['uid']}-{$input['sid']}-{$input['number']}";
//        $cache = cache($key);
//        if ($cache) {
//            return returnJson(1, '为防止重复充值,请1分钟后再试');
//        }
//        cache($key, 1, 60);
        UserModel::changeMoney($input['uid']?$input['uid']:0, 2, $input['number'], $input['note'], '', [
            'manager_name' => $this->manager['name'],
            'is_charge' => 1,
            'thumb' => $input['thumb'],
            'is_has' => $input['is_has']
        ], $input['sid']);
        if (!$input['is_has']) {
            $student = studentModel::getOne(['id' => $input['sid']]);
            studentModel::setFieldInc(['id' => $input['sid']], 'has_class_hour');//消除课时
            $student1 = studentModel::getOne(['id' => $input['sid']]);
            LogService::S()->writeLog('kaoqin', $this->manager['id'], ['input' => $input, 'student_old' =>$student,'student_new'=>$student1 ],$input['sid']);
        }
        return returnJson(0, '充值成功');
    }


    /* 充值积分 */
    public function chrgeScoreCla()
    {
        $input = input();
        if (!$input['number'] || !is_numeric($input['number'])) {
            return returnJson(1, '金额填写错误');
        }
        if (!$input['note']) {
            return returnJson(1, '请填写备注');
        }
        if (!$input['thumb']) {
            return returnJson(1, '请上传考勤图片');
        }
        if (!$input['sids']) {

            return returnJson(1, '请选择学员');
        }

//        $key = "charge-0-{$input['number']}";
//        $cache = cache($key);
//        if ($cache) {
//            return returnJson(1, '为防止重复充值,请1分钟后再试');
//        }
//        cache($key, 1, 60);
        $all = [];

        foreach ($input['sids'] as $value) {
            foreach ($value as $val) {
                $userStu = UserStudent::getOne(['sid' => $val]);
                if ($userStu) {
                    $all[] = [
                        'uid' => $userStu['uid'],
                        'sid' => $val
                    ];
                } else {
                    $all[] = [
                        'uid' => 0,
                        'sid' => $val
                    ];
                }
            }
        }
        if ($all) {
            $log = [];
            foreach ($all as $value) {
                UserModel::changeMoney($value['uid'], 2, $input['number'], $input['note'], '', [
                    'manager_name' => $this->manager['name'],
                    'is_charge' => 1,
                    'thumb' => $input['thumb'],
                    'is_has' => $input['is_has']
                ], $value['sid']);
                if (!$input['is_has']) {
                    $student = studentModel::getOne(['id' => $value['sid']]);
                    studentModel::setFieldInc(['id' => $value['sid']], 'has_class_hour');//消除课时
                    $student1 = studentModel::getOne(['id' => $value['sid']]);
                    $add['type'] = 'kaoqin';
                    $add['info'] = $this->manager['id'];
                    $add['data'] = json_encode(['input' => $input, 'student_old' => $student, 'student_new' => $student1]);
                    $add['create_time'] = date('Y-m-d H:i:s');
                    $add['api'] = $_SERVER['REQUEST_URI'];
                    $add['remark'] = $value['sid'];
                    $log[] = $add;
                }
            }

            if($log){
                LogService::S()->writeLogs($log);
            }

        }

        return returnJson(0, '充值成功');
    }

    /**
     * 所有学生
     * @return \think\response\Json
     */
    public function student_all()
    {    $where = array();
        $data = input('');
        if ($data['cid']) {
            if(!$data['id']){
                $where['id'] = array('in',ClassesStu::getColumn(['cid'=>$data['cid']],'sid'));
            }
        }
        $student = \app\common\model\Student::getAll($where, '', 'id,name');
        return returnJson(0, '', $student);
    }

    /**
     * 绑定学员
     * @return \think\response\Json
     */
    public function student_bind()
    {
        $uids = \app\common\model\UserStudent::getColumn(['sid' => input('sid', 0)], 'uid');
        if ($uids) {
            $user_student = \app\common\model\User::getAll(['id' => ['in', $uids]], '', 'id,nickname');
        } else {
            $user_student = [];
        }
        return returnJson(0, '', $user_student);
    }

    /* 打款 */
    public function atmConfirm()
    {
        $input = input();
        if (!$input['id']) {
            return returnJson(1, '提现记录不存在');
        }
        $log = WithdrawalModel::getOne([
            'id' => $input['id']
        ]);
        if (!$log || $log['status'] != 1) {
            return returnJson(1, '提现记录已处理');
        }
        if ($log['bank_name'] == '微信钱包') {
            $userInfo = UserModel::getOneById($log['uid']);
            $result = PayService::S(['mall_id' => 1])->qiyePay($log, $userInfo);
            if ($result === true) {
                $save = [
                    'status' => 2,
                    'update_time' => time()
                ];
                $res = WithdrawalModel::where('id', $log['id'])->update($save);
                if ($res) {
                    return returnJson(0, '审核成功');
                } else {
                    return returnJson(0, '审核失败请重试');
                }
            } else {
                return returnJson(0, $result);
            }

        } else {
            $save = [
                'status' => 2,
                'update_time' => time()
            ];
            $res = WithdrawalModel::where('id', $log['id'])->update($save);
            if ($res) {
                return returnJson(0, '审核成功');
            } else {
                return returnJson(0, '审核失败请重试');
            }
        }
    }

    /* 拒绝 */
    public function atmRefund()
    {
        $input = input();
        if (!$input['id']) {
            return returnJson(1, '提现记录不存在');
        }
        $log = WithdrawalModel::getOne([
            'id' => $input['id']
        ]);
        if (!$log || $log['status'] != 1) {
            return returnJson(1, '提现记录已处理');
        }
        $save = [
            'status' => 3,
            'update_time' => time()
        ];
        $res = WithdrawalModel::where('id', $log['id'])->update($save);
        if ($res) {
            UserModel::changeMoney($log['uid'], 1, $log['money'], '提现退回', false, [
                'manager_name' => $this->manager['name']
            ]);
            return returnJson(0, '已退回');
        } else {
            return returnJson(0, '处理失败请重试');
        }
    }

    public function orderShoufei()
    {
        $where = array(
            'pay_money' => array('<=', 1500)
        );
        $student = Student::getAll($where, 'id desc', 'id,name,class_hour,has_class_hour');
        $config = Config::getColumn(array(), 'name,value');
        $save = array();
        foreach ($student as $value) {
            $save[] = [
                'money' => $value['has_class_hour']<$config['keshi']?$config['keshi']*$config['keshi_shoufei']:$value['has_class_hour']*$config['keshi_shoufei'],
                'sid' => $value['sid'],
                'has_class_hour' => $value['has_class_hour'],
                'order_sn' => create_order_sn($value['sid'], 'SF'),
                'mid' => 32,
                'update_time' => time(),
                'create_time' => time()
            ];
        }
        
    }

    public function shoufeiGuanbi(){
        $input = input('');
        $save_data = array(
            'update_time' => time(),
            'checked' => 2
        )                ;
        OrderShoufei::update($save_data,array('id'=>array('eq',$input['id'])))   ;

        return returnJson(0, '已关闭交易');
    }
}
